<?php

namespace app\admin\controller;

use think\Controller;
use app\admin\model\Course;
use app\admin\model\Category;
use app\admin\model\CourseTag;
use think\Request;

class Courses extends Controller
{
    public function index()
    {
        $courses = Course::with('photo,tags,chapters')->order('id', 'desc')->paginate(10);
//        dump($courses);exit;

        return view('Courses/index', compact('courses'));
    }

    public function create()
    {
        $views = Category::with('tags')->order('id', 'desc')->select();

        return view('Courses/create', compact('views'));
    }

    public function save(Request $request)
    {
//        dump($request->param()) ;exit;
        $param['tag_ids'] = $request->param('tag_id/a');
        $course = Course::create($request->param());
        $data['course_id'] = $course->id;
        foreach ($param['tag_ids'] as $data['tag_id']) {
            CourseTag::create($data);
        }
        return redirect('Courses/index');
    }

    /***加载编辑页面
     * @param $id
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit($id)
    {
        $views = Category::with('tags')->order('id', 'desc')->select();

        $course = Course::with('photo,tags,chapters')->find($id);
        $param = implode(',', array_column($course->tags->toArray(), 'id'));
//        dump($param);
//        exit;

        return view('Courses/edit', compact('views', 'course', 'param'));
    }

    /***保存编辑内容
     * @param Request $request
     * @param $id
     * @return \think\response\Redirect
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function update(Request $request, $id)
    {
//        dump($request->param());exit;
        $param['tag_ids'] = $request->param('tag_id/a');
        $course = Course::with('photo,tags')->find($id);
        CourseTag::where('course_id', $id)->delete();
        $course->allowField(true)->save($request->param(), ['id' => $id]);
        $data['course_id'] = $course->id;
        foreach ($param['tag_ids'] as $data['tag_id']) {
            CourseTag::create($data);
        }
        return redirect('Courses/index');
    }

    public function delete($id)
    {
        Course::destroy($id);
        CourseTag::where('course_id', $id)->delete();
        return redirect('Courses/index');
    }

}